package com.jjsj.framework.web.service;

import cn.hutool.core.util.StrUtil;
import com.jjsj.common.constant.Constants;
import com.jjsj.common.core.domain.model.LoginUser;
import com.jjsj.common.core.redis.RedisCache;
import com.jjsj.common.exception.CustomException;
import com.jjsj.common.exception.user.CaptchaException;
import com.jjsj.common.exception.user.CaptchaExpireException;
import com.jjsj.common.exception.user.UserLoginLimitException;
import com.jjsj.common.exception.user.UserPasswordNotMatchException;
import com.jjsj.common.utils.MessageUtils;
import com.jjsj.framework.manager.AsyncManager;
import com.jjsj.framework.manager.factory.AsyncFactory;
import com.jjsj.system.constant.UserConstants;
import com.jjsj.system.singleton.UserLoginCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        Integer count = UserLoginCount.getInstance().map.get(username);
        if (count != null && count > 4) {
            throw new UserLoginLimitException(new Integer[]{count - 2});
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));

                if (count == null) {
                    UserLoginCount.getInstance().map.put(username, 1);
                } else {
                    UserLoginCount.getInstance().map.put(username, UserLoginCount.getInstance().map.get(username) + 1);
                }
                if (count != null && count > 3) {
                    String keyRedis = String.valueOf(StrUtil.format("{}:{}", UserConstants.REDIS_USER_KEY_EXPIRE, username));
                    redisTemplate.opsForValue().set(keyRedis, username, 10, TimeUnit.MINUTES);//设置过期时间
                    throw new UserLoginLimitException(new Integer[]{count - 1});
                }
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (count != null) {
            UserLoginCount.getInstance().map.remove(username);
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
